<template>
  <div style="max-width: 400px; margin: 20px auto">
    <el-select
      v-model="selectedCategory"
      placeholder="请选择分类"
      style="width: 150px"
      @change="handleCategoryChange"
    >
      <el-option
        label="水果"
        value="fruits"
      />
      <el-option
        label="动物"
        value="animals"
      />
      <el-option
        label="国家"
        value="countries"
      />
    </el-select>

    <!-- 通过绑定key，切换selectedCategory时强制重新渲染el-autocomplete -->
    <el-autocomplete
      :key="autocompleteKey"
      v-model="inputValue"
      :fetch-suggestions="querySearch"
      :trigger-on-focus="false"
      placeholder="请输入内容"
      style="width: 220px; margin-left: 10px"
      @select="handleSelect"
    />
  </div>
</template>

<script lang="ts" setup>
import { ref, computed } from "vue";

const selectedCategory = ref("fruits");
const inputValue = ref("");

// 切换select后更新key, 强制重新渲染autocomplete 组件
// 维护一个key，用于强制重新渲染el-autocomplete
const autocompleteKey = computed(
  () => `autocomplete-${selectedCategory.value}`
);

const optionsMap: Record<string, string[]> = {
  fruits: ["苹果", "1122", "2211", "1111", "2222", "33221"],
  animals: ["猫", "111111", "22222", "3333", "2233", "熊"],
  countries: ["中国", "11111111", "12121", "3333", "4444", "巴西"],
};

function querySearch(
  queryString: string,
  cb: (results: { value: string }[]) => void
) {
  const list = optionsMap[selectedCategory.value] || [];
  const results = list
    .filter((item) => item.includes(queryString))
    .map((item) => ({ value: item }));
  cb(results);
}

function handleCategoryChange(val: string) {
  inputValue.value = ""; // 切换分类时清空输入框
  // 不需要额外操作，autocompleteKey会自动更新，触发重新渲染
}

function handleSelect(item: { value: string }) {
  inputValue.value = item.value;
}
</script>

<style scoped>
/* 你可以根据需要自定义样式 */
</style>
